/**
 * Created by xiaojing on 2017/2/5 0005.
 */
var express = require('express');
var config = require('../../config');
var router = express.Router();
var mysql = require('../common/mysqldb');
var mongodb = require('../common/mongodb');
var jade = require('jade');
var less = require('less');
var fs = require('fs');
var util = require('../common/util');
var path = require('path');
var archiver = require('archiver');
var ChatMessageModel = require('../models/ChatMessage');
var Q = require('q');

/* GET home page. */
router.get('/:orderid', function (req, res, next) {
    var orderid = req.params.orderid;
    var exportDir = __dirname + '/' + orderid;
    initExports(exportDir, orderid, function (status) {
        if (status == 0) {
            Q.all([Q.fcall(readLESS).then(renderCSS).then(renderHTML), readChatHistory(orderid, exportDir)]).then(function (results) {
                if (results[0]) {
                    fs.writeFileSync(exportDir + '/' + config.exportChatFileName + '.html', results[0]);
                    packageExports(exportDir, orderid, function (err, zippath, urlpath) {
                        if (!err) {
                            res.json({code: 0, msg: '导出成功', response: {packageurl: urlpath}});
                        } else {
                            res.json({code: 2, msg: '导出失败', response: err});
                        }
                    });
                }
            }).catch(function (error) {
                console.log(error);
                util.deleteFolder(exportDir);
            });
        } else if (status == 1) {
            res.json({code: 1, msg: '导出正在进行，请稍等'});
        } else if (status == 2) {
            res.json({code: 2, msg: '导出失败'});
        } else if (status == 3) {
            res.json({
                code: 3,
                msg: '已存在证据包',
                response: {packageurl: '/exports/' + orderid + '.zip'}
            });
        }
    });
});

/**
 * 创建导出文件夹
 * @param dir
 * @param cb 回调，导出正在进行返回1，创建导出文件夹失败返回2，返回3表示已经生成过zip包了，直接使用即可，正常返回0
 */
function initExports(dir, orderid, cb) {
    fs.exists(dir, function (exists) {
        if (!exists) {
            var zippath = config.rootDir + '/public/exports/' + orderid + '.zip';
            fs.exists(zippath, function (exists) {
                if (exists) {
                    cb(3);//已存在
                }else{
                    fs.mkdir(dir, function (err) {
                        if (err) {
                            cb(2);//创建文件夹失败
                        } else {
                            cb(0);//创建文件夹成功
                        }
                    });
                }
            });
        } else {
            cb(1);
        }
    });
}

/**
 * 读取导出聊天记录的less样式文件
 * @returns {Promise}
 */
function readLESS() {
    return new Promise(function (resolve, reject) {
        fs.readFile(__dirname + '/chatviews.less', function (err, data) {
            if (!err) {
                var css = data.toString();
                resolve(css);
            } else {
                reject(err);
            }
        });
    });
}

/**
 * 渲染less文件为css
 * @param lessdata
 * @returns {Promise}
 */
function renderCSS(lessdata) {
    return new Promise(function (resolve, reject) {
        less.render(lessdata, {compress: true}, function (e, output) {
            // renderPage(res,output.css);
            if (e) {
                reject(e);
            } else {
                resolve(output.css);
            }
        });
    });
}

/**
 * 读取聊天记录，并写入文件
 * @returns {Promise}
 */
function readChatHistory(orderid, dir) {
    return new Promise(function (resolve, reject) {
        ChatMessageModel.find({}, function (err, data) {
            if (err) {
                reject(err);
            } else {
                var datadir = dir + '/data';
                fs.mkdir(datadir, function (err) {
                    if (!err) {
                        var filename = datadir + '/chatdata.json';
                        fs.writeFileSync(filename, JSON.stringify(data));
                        resolve(filename);
                    }
                });

            }
        });
    });
}

/**
 * 渲染聊天记录的html
 * @param css 聊天记录的样式
 * @returns {Promise}
 */
function renderHTML(css) {
    return new Promise(function (resolve, reject) {
        jade.renderFile('views/chatviews.jade', {
            title: 'fucking shit',
            chatstyles: css
        }, function (err, html) {
            if (err) {
                reject(err);
            } else {
                resolve(html);
            }
        });
    });
}

/**
 * 将导出的文件打包为zip
 * @param exportDir 导出的文件根目录
 * @param orderid 订单id(根目录名称)
 * @param cb 回调
 */
function packageExports(exportDir, orderid, cb) {
    var zippath = config.rootDir + '/public/exports/' + orderid + '.zip';
    var output = fs.createWriteStream(zippath);
    var ziparchiver = archiver('zip');
    output.on('close', function () {
        util.deleteFolder(exportDir);
        cb(null, zippath, '/exports/' + orderid + '.zip');
    });
    ziparchiver.on('error', function (err) {
        cb(err);
    });
    ziparchiver.pipe(output);
    ziparchiver.bulk([
        {expand: true, cwd: exportDir, src: ['**'], dest: orderid}
    ]);
    ziparchiver.finalize();
}

module.exports = router;